<template>
  <div class="user-management">
    <!-- <div class="page-header">
      <h2>用户管理</h2>
      <p>管理平台所有用户，包括用户信息维护、状态管理等</p>
    </div> -->

    <!-- 顶部统计卡片 -->
    <div class="stats-cards" v-loading="statsLoading">
      <div class="stat-card">
        <div class="stat-icon total">
          <i class="el-icon-user"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ userStats.totalCount || 0 }}</div>
          <div class="stat-label">用户总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon normal">
          <i class="el-icon-check"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ userStats.normalCount || 0 }}</div>
          <div class="stat-label">正常用户</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon disabled">
          <i class="el-icon-close"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ userStats.disabledCount || 0 }}</div>
          <div class="stat-label">禁用用户</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon admin">
          <i class="el-icon-setting"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ userStats.adminCount || 0 }}</div>
          <div class="stat-label">管理员</div>
        </div>
      </div>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索用户昵称"
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-select v-model="searchForm.userType" placeholder="用户类型" clearable>
          <el-option label="普通用户" :value="0" />
          <el-option label="管理员" :value="1" />
        </el-select>
        <el-select v-model="searchForm.status" placeholder="用户状态" clearable>
          <el-option label="正常" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch" :loading="loading">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </div>
      <div class="action-section">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增用户</el-button>
        <el-button
          type="warning"
          icon="el-icon-close"
          :disabled="selectedUserIds.length === 0"
          @click="handleBatchStatusChange(1)"
        >
          批量禁用
        </el-button>
        <el-button
          type="success"
          icon="el-icon-check"
          :disabled="selectedUserIds.length === 0"
          @click="handleBatchStatusChange(0)"
        >
          批量启用
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          :disabled="selectedUserIds.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        row-key="id"
        stripe
        border
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div class="user-info-cell">
              <el-avatar :size="40" :src="scope.row.avatarUrl" class="user-avatar">
                {{ scope.row.nickname?.[0] }}
              </el-avatar>
              <div class="user-details">
                <div class="user-name">{{ scope.row.nickname || '未设置' }}</div>
                <div class="user-extra">ID: {{ scope.row.id }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130">
          <template #default="scope">
            {{ scope.row.phone || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="150">
          <template #default="scope">
            {{ scope.row.email || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="地区" width="150">
          <template #default="scope">
            <span v-if="scope.row.province || scope.row.city">
              {{ scope.row.province || '' }}{{ scope.row.city || '' }}
            </span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="userType" label="用户类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.userType === 1 ? 'danger' : 'info'">
              {{ scope.row.userType === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'warning'">
              {{ scope.row.status === 0 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="80">
          <template #default="scope">
            {{ scope.row.points || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                <i class="el-icon-edit"></i>编辑
              </el-button>
              <el-button 
                size="small" 
                :type="scope.row.status === 0 ? 'warning' : 'success'"
                @click="handleToggleStatus(scope.row)"
              >
                <i :class="scope.row.status === 0 ? 'el-icon-close' : 'el-icon-check'"></i>
                {{ scope.row.status === 0 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="info" @click="handleResetPassword(scope.row)">
                <i class="el-icon-key"></i>重置密码
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                <i class="el-icon-delete"></i>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ pagination.total }} 条数据
      </div>
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="userForm.nickname" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" placeholder="请选择性别" clearable>
                <el-option label="未知" :value="0" />
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-input v-model="userForm.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="userForm.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="userForm.userType" placeholder="请选择用户类型">
                <el-option label="普通用户" :value="0" />
                <el-option label="管理员" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态" prop="status">
              <el-select v-model="userForm.status" placeholder="请选择用户状态">
                <el-option label="正常" :value="0" />
                <el-option label="禁用" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="!userForm.id">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="userForm.password"
                type="password"
                placeholder="可选，不填写将使用默认密码123456"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="初始积分" prop="points">
              <el-input-number v-model="userForm.points" :min="0" :max="99999" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="userForm.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserList, 
  createUser, 
  updateUser, 
  deleteUser,
  batchDeleteUsers,
  updateUserStatus,
  batchUpdateUserStatus,
  resetUserPassword,
  getUserStats
} from '@/api/admin'

export default {
  name: 'UserManagement',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const statsLoading = ref(false)
    const submitLoading = ref(false)
    const userList = ref([])
    const userStats = ref({})
    const selectedUserIds = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      userType: null,
      status: null
    })
    
    // 分页
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 对话框
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const userFormRef = ref(null)
    
    // 用户表单
    const userForm = reactive({
      id: null,
      nickname: '',
      phone: '',
      email: '',
      gender: 0,
      province: '',
      city: '',
      userType: 0,
      status: 0,
      points: 0,
      password: '',
      remark: ''
    })
    
    // 表单验证规则
    const userRules = {
      nickname: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '用户昵称长度为2-20个字符', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { min: 6, message: '密码长度至少6位', trigger: 'blur' }
      ],
      userType: [
        { required: true, message: '请选择用户类型', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择用户状态', trigger: 'change' }
      ]
    }
    
    // 获取用户列表
    const fetchUserList = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.page,
          size: pagination.size,
          ...searchForm
        }
        const response = await getUserList(params)
        if (response.code === 200) {
          userList.value = response.data.records || []
          pagination.total = response.data.total || 0
        } else {
          ElMessage.error(response.message || '获取用户列表失败')
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }
    
    // 获取用户统计
    const fetchUserStats = async () => {
      try {
        statsLoading.value = true
        const response = await getUserStats()
        if (response.code === 200) {
          userStats.value = response.data || {}
        } else {
          console.error('获取用户统计失败:', response.message)
        }
      } catch (error) {
        console.error('获取用户统计失败:', error)
      } finally {
        statsLoading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      fetchUserList()
    }
    
    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        keyword: '',
        userType: null,
        status: null
      })
      handleSearch()
    }
    
    // 新增用户
    const handleAdd = () => {
      resetUserForm()
      dialogTitle.value = '新增用户'
      dialogVisible.value = true
      // 新增用户时密码可选，如果不填写将使用默认密码123456
      userRules.password[0] = { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    }
    
    // 编辑用户
    const handleEdit = (row) => {
      resetUserForm()
      Object.assign(userForm, {
        ...row,
        password: '' // 编辑时不显示密码
      })
      dialogTitle.value = '编辑用户'
      dialogVisible.value = true
      // 编辑用户时密码非必填
      userRules.password = [
        { min: 6, message: '密码长度至少6位', trigger: 'blur' }
      ]
    }
    
    // 切换用户状态
    const handleToggleStatus = async (row) => {
      const newStatus = row.status === 0 ? 1 : 0
      const action = newStatus === 0 ? '启用' : '禁用'
      
      try {
        await ElMessageBox.confirm(`确定要${action}用户 "${row.nickname}" 吗？`, '确认操作')
        await updateUserStatus(row.id, newStatus)
        ElMessage.success(`${action}成功`)
        fetchUserList()
        fetchUserStats()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`${action}失败: ` + error.message)
        }
      }
    }
    
    // 重置密码
    const handleResetPassword = async (row) => {
      try {
        await ElMessageBox.prompt('请输入新密码', '重置密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'password',
          inputValidator: (value) => {
            if (!value || value.length < 6) {
              return '密码长度至少6位'
            }
            return true
          }
        })
        
        const newPassword = arguments[0].value
        await resetUserPassword(row.id, newPassword)
        ElMessage.success('密码重置成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('重置密码失败: ' + error.message)
        }
      }
    }
    
    // 删除用户
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确定要删除用户 "${row.nickname}" 吗？`, '确认删除', {
          type: 'warning'
        })
        await deleteUser(row.id)
        ElMessage.success('删除成功')
        fetchUserList()
        fetchUserStats()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败: ' + error.message)
        }
      }
    }
    
    // 批量操作
    const handleSelectionChange = (selection) => {
      selectedUserIds.value = selection.map(item => item.id)
    }
    
    const handleBatchStatusChange = async (status) => {
      if (selectedUserIds.value.length === 0) {
        ElMessage.warning('请选择要操作的用户')
        return
      }
      
      const action = status === 0 ? '启用' : '禁用'
      try {
        await ElMessageBox.confirm(`确定要${action}选中的 ${selectedUserIds.value.length} 个用户吗？`, '确认操作')
        await batchUpdateUserStatus(selectedUserIds.value, status)
        ElMessage.success(`批量${action}成功`)
        fetchUserList()
        fetchUserStats()
        selectedUserIds.value = []
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`批量${action}失败: ` + error.message)
        }
      }
    }
    
    const handleBatchDelete = async () => {
      if (selectedUserIds.value.length === 0) {
        ElMessage.warning('请选择要删除的用户')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedUserIds.value.length} 个用户吗？`, '确认删除', {
          type: 'warning'
        })
        await batchDeleteUsers(selectedUserIds.value)
        ElMessage.success('批量删除成功')
        fetchUserList()
        fetchUserStats()
        selectedUserIds.value = []
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败: ' + error.message)
        }
      }
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.page = 1
      fetchUserList()
    }
    
    const handleCurrentChange = (page) => {
      pagination.page = page
      fetchUserList()
    }
    
    // 对话框操作
    const handleDialogClose = () => {
      dialogVisible.value = false
      resetUserForm()
    }
    
    const handleSubmit = async () => {
      if (!userFormRef.value) return
      
      await userFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            submitLoading.value = true
            if (userForm.id) {
              // 编辑
              await updateUser(userForm.id, userForm)
              ElMessage.success('更新成功')
            } else {
              // 新增
              await createUser(userForm)
              ElMessage.success('创建成功')
            }
            handleDialogClose()
            fetchUserList()
            fetchUserStats()
          } catch (error) {
            ElMessage.error('操作失败: ' + error.message)
          } finally {
            submitLoading.value = false
          }
        }
      })
    }
    
    // 重置表单
    const resetUserForm = () => {
      Object.assign(userForm, {
        id: null,
        nickname: '',
        phone: '',
        email: '',
        gender: 0,
        province: '',
        city: '',
        userType: 0,
        status: 0,
        points: 0,
        password: '',
        remark: ''
      })
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }
    
    // 时间格式化
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchUserList()
      fetchUserStats()
    })
    
    return {
      loading,
      statsLoading,
      submitLoading,
      userList,
      userStats,
      selectedUserIds,
      searchForm,
      pagination,
      dialogVisible,
      dialogTitle,
      userForm,
      userRules,
      userFormRef,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleToggleStatus,
      handleResetPassword,
      handleDelete,
      handleSelectionChange,
      handleBatchStatusChange,
      handleBatchDelete,
      handleSizeChange,
      handleCurrentChange,
      handleDialogClose,
      handleSubmit,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px;
  color: #1a1a1a;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  margin-right: 16px;
}

.stat-icon.total { background-color: #409eff; }
.stat-icon.normal { background-color: #67c23a; }
.stat-icon.disabled { background-color: #f56c6c; }
.stat-icon.admin { background-color: #e6a23c; }

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 13px;
  color: #606266;
}

/* 工具栏 */
.toolbar {
  background: white;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  border: 1px solid #e4e7ed;
}

.search-section {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.search-section .el-input {
  width: 200px;
}

.search-section .el-select {
  width: 120px;
}

.action-section {
  display: flex;
  gap: 8px;
}

/* 表格容器 */
.table-container {
  background: white;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.user-info-cell {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #1a1a1a;
  margin-bottom: 2px;
}

.user-extra {
  font-size: 12px;
  color: #999;
}

.text-placeholder {
  color: #c0c4cc;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

/* 对话框 */
.dialog-footer {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .user-management {
    padding: 12px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-section {
    justify-content: center;
  }

  .search-section .el-input,
  .search-section .el-select {
    width: 100%;
    max-width: 200px;
  }

  .action-section {
    justify-content: center;
    flex-wrap: wrap;
  }

  .pagination-container {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
}
</style>